import mediapipe as mp
import cv2
import time

camera = cv2.VideoCapture(0)
mpDraw = mp.solutions.drawing_utils
hands = mp.solutions.hands
cTime = 0
nTime = 0
with hands.Hands() as hand:
    while camera.isOpened():
        # 读取当前帧图像
        flag, img = camera.read()
        if not flag:
            continue
        # 使摄像头反转
        img = cv2.flip(img, 1)
        #
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        # 手势识别
        results = hand.process(imgRGB)
        if results.multi_hand_landmarks:
            for handLms in results.multi_hand_landmarks:
                for id, lm in enumerate(handLms.landmark):
                    height, width, c = img.shape
                    cx, cy = int(lm.x * width), int(lm.y * height)
                    print(id,cx,cy)
                    cv2.circle(img,(cx,cy),10,(0,100,100),cv2.FILLED)
                mpDraw.draw_landmarks(img, handLms,hands.HAND_CONNECTIONS)
        # 计算FPS
        nTime = time.time()
        fps = 1 / (nTime - cTime)
        cTime = nTime
        # 为当前帧添加fps标识
        cv2.putText(img, f"FPS:{int(fps)}", (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 3)

        # 显示
        cv2.imshow("camera", img)
        if cv2.waitKey(5) & 0xff == ord('q'):
            break
camera.release()